package com.lzw.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.lzw.bean.*;
import com.lzw.common.bean.Result;
import com.lzw.common.controller.BaseController;
import com.lzw.common.service.impl.CommonService;
import com.lzw.common.tool.CookieTool;
import com.lzw.common.tool.KaptchaTool;
import com.lzw.mapper.UserMapper;
import com.lzw.param.user.Page;
import com.lzw.service.NodeService;
import com.lzw.service.RoleService;
import com.lzw.service.UserRoleService;
import com.lzw.service.UserService;
import com.lzw.service.impl.UserRoleServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.net.HttpCookie;
import java.util.List;

/**
 * Created by 林志伟 on 2017/5/11.
 */
@Controller()
@RequestMapping("/user")
public class UserController extends BaseController {

    @Autowired
    UserService userService;



    @GetMapping("/index")
    public String  index(Model model, Page page){
        System.out.println("分页数据"+page);
        PageInfo pageInfo= userService.page(page);
        logger.info("用户列表："+ JSON.toJSONString(pageInfo));
        model.addAttribute("pageInfo",pageInfo);
        return this.getTemplateName();
    }

    @GetMapping("/add")
    public String add(Model model){
        return this.getTemplateName();
    }

    @PostMapping("/add")
    @ResponseBody
    public Result addPost(@Valid User user, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            logger.info("验证错误："+bindingResult.getFieldError().getDefaultMessage());
            return CommonService.error(bindingResult.getFieldError().getDefaultMessage());
        }
        System.out.println("注入user:"+user.toString());
        Result result=userService.insert(user);
        return result;
    }

    @GetMapping("/update")
    public String update(@RequestParam int id,Model model){
        User user =userService.find(id);
        if(user==null){
            //错误页面
        }
        model.addAttribute("user",user);
        return this.getTemplateName();
    }

    @ResponseBody
    @PostMapping("/update")
    public Result updatePost(User user){

        return userService.update(user);
    }

    @PostMapping("/delete")
    @ResponseBody
    public  Result delete(@RequestParam("id[]") int[] ids){
        for (int i=0;i<ids.length;i++){
            logger.info("删除ids:"+ids[i]);
        }
        return  userService.deleteAll(ids);
    }

    /**
     * 启用
     * @param id
     * @return
     */
    @PostMapping("/open")
    @ResponseBody
    public Result open(@RequestParam("id") int id){

        return  userService.open(id);
    }


    /**
     * 禁用
     * @param id
     * @return
     */
    @PostMapping("/close")
    @ResponseBody
    public Result close(@RequestParam("id") int id){

        return  userService.close(id);
    }



    /**
     * 登录
     * @return
     */
    @PostMapping("/login")
    @ResponseBody
    public Result login(String name, String password, String code){
        KaptchaTool kaptchaTool= new KaptchaTool(request.getSession());
        if(!kaptchaTool.check(code)){
            return  CommonService.error("验证码错误！");
        }


        return  userService.login(name,password, new CookieTool(request,response));
    }

    @GetMapping("/logout")
    public String logout(){
        userService.logout(new CookieTool(request,response));
        return  "redirect:/login";
    }

    private @Autowired RoleService roleService;
    private @Autowired UserRoleService userRoleService;
    @GetMapping("/setRole")
    public String  setRole(@RequestParam("user_id")  int user_id,Model model){
        List<Role> roles=roleService.selectByUser(user_id);
        model.addAttribute("roles",roles);
        User user=userService.find(user_id);
        model.addAttribute("user",user);
        return  this.getTemplateName();
    }

    /**
     * 修改授权信息
     * @param user_id
     * @param role_ids
     * @return
     */
    @PostMapping("/setRole")
    @ResponseBody
    public Result setRolePost(@RequestParam("user_id")  int user_id,@RequestParam("role_ids[]") int[] role_ids){
        return  userRoleService.setRole(user_id,role_ids);
    }


}
